package com.idbk.chargestation.activity.user;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.assist.ActivityLicense;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonBase;
import com.idbk.chargestation.bean.JsonLogin;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.DateUtils;
import com.idbk.chargestation.util.GsonUtils;

import java.lang.ref.WeakReference;
import java.util.Date;

/**
 * 注册页面
 *
 * @author lupc, zhx
 */
public class ActivityRegister extends BaseActivity implements OnClickListener {

    private static final String TAG = ActivityRegister.class.getSimpleName();
    private Context mContext;
    private Button mBtnVcode;
    private EditText mEdtUsername, mEdtPassword, mEdtVcode;
    private TextView mTexLicense;
    private ImageView mImgPasswordStyle;
    private String mUsername, mPassword, mVcode;
    private boolean mIsPasswordShowFlag = false;
    private static int mCount;
    private static MyHandle mHandle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_register);

        mContext = this;

        initView();
    }

    private void initView() {
        initWidgetView();
        initOnClickView();
    }

    private void initWidgetView() {
        mEdtUsername = (EditText) findViewById(R.id.edittext_username);
        mEdtVcode = (EditText) findViewById(R.id.edittext_vcode);
        mEdtPassword = (EditText) findViewById(R.id.edittext_password);
        mTexLicense = (TextView) findViewById(R.id.textview_license);
        if (mTexLicense != null) {
            mTexLicense.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        }

        mBtnVcode = (Button) findViewById(R.id.button_get_vcode);
        mImgPasswordStyle = (ImageView) findViewById(R.id.button_showpassword);
    }

    @SuppressWarnings("ConstantConditions")
    private void initOnClickView() {
        mBtnVcode.setOnClickListener(this);
        mImgPasswordStyle.setOnClickListener(this);
        mTexLicense.setOnClickListener(this);
        findViewById(R.id.button_submit).setOnClickListener(this);
        findViewById(R.id.toolbar_back).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_submit:  //点击注册按钮
                gotoRegister();
                break;
            case R.id.button_get_vcode:  //点击获取验证码按钮
                getVcode();
                break;
            case R.id.button_showpassword://明文和暗文
                changePwdStyle();
                break;
            case R.id.textview_license:
                showLicense();
                break;
            case R.id.toolbar_back:
                finish();
                break;
            default:
                break;
        }
    }

    private void showLicense() {
        Intent intent = new Intent(this, ActivityLicense.class);
        startActivity(intent);
    }

    private void gotoRegister() {
        if (checkInput()) {
            register();
        }
    }

    private boolean checkInput() {
        mUsername = mEdtUsername.getText().toString();
        mPassword = mEdtPassword.getText().toString();
        mVcode = mEdtVcode.getText().toString();
        if (mUsername.equals("") || (mUsername.length() != 11)) {
            Toast.makeText(this, this.getResources().getString(R.string.tip_please_input_username), Toast.LENGTH_SHORT).show();
            mEdtUsername.setFocusable(true);
            return false;
        }
        if (mPassword.equals("") || mPassword.length() < 6 || mPassword.length() > 20) {
            Toast.makeText(this, this.getResources().getString(R.string.tip_please_input_password), Toast.LENGTH_SHORT).show();
            mEdtPassword.setFocusable(true);
            return false;
        }
        if (mVcode.equals("") || mVcode.length() != 6) {
            Toast.makeText(this, this.getResources().getString(R.string.tip_please_input_checkcode), Toast.LENGTH_SHORT).show();
            mEdtVcode.setText("");
            mEdtVcode.setFocusable(true);
            return false;
        }
        return true;
    }

    private void register() {
        showMyProgressDialog(true, false, "提交中...");
        AppContext ac = AppContext.getInstance();
        mMainRequest = ChargeStationAPI.register(mUsername, mPassword, mVcode, ac.getPushClientId(), mCallBack);
    }

    private EHttpResponse mCallBack = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonLogin result = GsonUtils.toBean(JsonLogin.class, response);
            if (handleResponseStatus(ActivityRegister.this, result)) {
                Toast.makeText(ActivityRegister.this, R.string.register_success, Toast.LENGTH_SHORT).show();
                AppContext.getInstance().saveUserInfo(result.token, mUsername, mPassword, result.outTime);
                setResult(Const.CODE_RESPONSE_LOGIN_SUCCESS);
                finish();
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            Log.e(TAG, error.getMessage(), error.getCause());
            Toast.makeText(ActivityRegister.this, R.string.common_tip_resultnull, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onEFinish() {
            dismissMyProgressDialog();
        }

    };

    private void getVcode() {
        if (checkPhoneNum()) {
            getCode();
        }
//        if (AppContext.getInstance().isGetCode()) {
//
//        } else {
//            Toast.makeText(this, "您已达到每天申请注册次数上限，请隔天再试", Toast.LENGTH_SHORT).show();
//        }
    }

    private boolean checkPhoneNum() {
        mUsername = mEdtUsername.getText().toString();
        if (mUsername.equals("") || mUsername.length() != 11) {
            Toast.makeText(ActivityRegister.this, R.string.tip_please_input_username, Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void getCode() {
        showMyProgressDialog(true, false, "发送中...");
        String timestamp = DateUtils.dateToString(new Date());
        String sign = getSign(timestamp);
        mMainRequest = ChargeStationAPI.getSimpleSMS(mUsername, true, timestamp, sign, mVcodeCallBall);
    }

    private String getSign(String timestamp) {
        String sign = "";
        try {
            AppContext ac = AppContext.getInstance();
            sign = ac.getSign(mUsername, timestamp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sign;
    }

    private EHttpResponse mVcodeCallBall = new EHttpResponse() {
        @Override
        public void onEResponse(String response) {
            JsonBase result = GsonUtils.toBean(JsonBase.class, response);
            if (handleResponseStatus(ActivityRegister.this, result)) {
                changeVcodeButtonStyle();
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            Toast.makeText(mContext, R.string.common_tip_resultfail, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onEFinish() {
            dismissMyProgressDialog();
        }
    };

    private void changeVcodeButtonStyle() {
        mBtnVcode.setClickable(false);
        String time = "120秒后重发";
        mBtnVcode.setText(time);
        mBtnVcode.setBackgroundResource(R.drawable.bg_vcode_down);
        mCount = 120;
        mHandle = new MyHandle(ActivityRegister.this);
        mHandle.sendEmptyMessageDelayed(1, 1000);
        Toast.makeText(mContext, R.string.common_sms_success, Toast.LENGTH_SHORT).show();
    }

    private static class MyHandle extends Handler {
        WeakReference<ActivityRegister> mActivity;

        MyHandle(ActivityRegister activity) {
            mActivity = new WeakReference<ActivityRegister>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            ActivityRegister theActivity = mActivity.get();
            if (theActivity == null)
                return;
            if (msg.what == 1) {
                mCount--;
                if (mCount < 1) {
                    theActivity.mBtnVcode.setClickable(true);
                    theActivity.mBtnVcode.setText(R.string.activity_register_getcheckCode);
                    theActivity.mBtnVcode.setBackgroundResource(R.drawable.bg_vcode_up);
                } else {
                    String time = mCount + "秒后重发";
                    theActivity.mBtnVcode.setText(time);
                    mHandle.sendEmptyMessageDelayed(1, 1000);
                }
            }
        }
    }

    //明文和暗文的转换
    private void changePwdStyle() {
        if (mIsPasswordShowFlag) {
            mIsPasswordShowFlag = false;
            mImgPasswordStyle.setImageResource(R.drawable.btn_login_password_visible);
            mEdtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            mIsPasswordShowFlag = true;
            mImgPasswordStyle.setImageResource(R.drawable.btn_login_password_hidden);
            mEdtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
    }

}



